package com.gyc.simple.zuul.filter;


import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.gyc.simple.common.exception.BaseException;
import com.gyc.simple.common.exception.BaseExceptionBody;
import com.gyc.simple.common.exception.CommonError;
import com.gyc.simple.common.util.JwtUtils;
import com.gyc.simple.common.vo.User;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 判断登录与否，校验jwt,封装header
 */
@Component
public class AuthFilter extends ZuulFilter {
	private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);
	//判断filter是否执行
	@Override
	public boolean shouldFilter() {
		// 判断是否需要进行处理
		RequestContext rc = RequestContext.getCurrentContext();
		return isLogin(rc);
	}

	@Override
	public Object run() {
		RequestContext rc = RequestContext.getCurrentContext();
		authUser(rc);
		return null;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	private boolean isLogin(RequestContext requestContext){
		HttpServletRequest request = requestContext.getRequest();
		String requestUrl = request.getContextPath();
		if("/login".equals(requestUrl)){
			return false;
		}
		return true;
	}
	
	private static Map<String, String> httpRequestToMap(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.put(headerName, request.getHeader(headerName));
        }
        return headers;
    }
	
	public static void authUser(RequestContext ctx) {
		HttpServletRequest request = ctx.getRequest();
		Map<String, String> header = httpRequestToMap(request);

		//取出token
		String token = header.get("Authentication");
		//校验token
		Map<String, Claim> claims = JwtUtils.verifyToken(token);
		String userid = claims.get("iuId").asString();
		String loginName = claims.get("iuLname").asString();

		if(StringUtils.isBlank(userid)||StringUtils.isBlank(userid)) {
			try {
				BaseException BaseException = new BaseException(CommonError.AUTH_EMPTY_ERROR.getCode(),CommonError.AUTH_EMPTY_ERROR.getCodeEn(),CommonError.AUTH_EMPTY_ERROR.getMessage(),1L);
				BaseExceptionBody errorBody = new BaseExceptionBody(BaseException);
				ctx.setSendZuulResponse(false);
				ctx.setResponseStatusCode(401);
				ctx.setResponseBody(JSONObject.toJSON(errorBody).toString());
			} catch (Exception e) {
				logger.error("println message error",e);
			}
		}else {
			header.put("iuId",userid);
			header.put("iuLname",loginName);
			for (Map.Entry<String, String> entry : header.entrySet()) {
				ctx.addZuulRequestHeader(entry.getKey(), entry.getValue());
			}
		}
	}
	
}
